<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class inovices {

    public function payment_invoice($user_id, $Temporary = true, $order_id = '', $dolar = '', $default_shipment_rate = '', $default_sescount = '') {
        $CI = & get_instance();
        // get if Temporary
        if ($Temporary == true) {
            $CI->db->where('temporary', 'YES');
        } elseif ($Temporary == false) {
            $CI->db->where('temporary', 'NO');
        }

        // get by user id
        if (!empty($user_id)) {
            $CI->db->where('user_id', $user_id);
        }

        if (!empty($order_id)) {
            $CI->db->where('order_id', $order_id);
        }

        // to order paid only
        $CI->db->where('type', 'item_paid');
        // get total pay ment price

        $CI->db->select_sum('(`quantity` * `price`) + `shiping_cost`', 'Payment_price');
        // get total weigth sum(weigth)
        $CI->db->select_sum('`quantity` * `weight`', 'Total_wiegth');
        // get total (quanitty);

        $CI->db->select_sum('`quantity`', 'Total_quantity');

        // get count (order);
        $CI->db->select('COUNT(*) AS Total_order', FALSE);


        $CI->db->from('items');
        $sql = $CI->db->get();
        // if found result
        if ($sql->num_rows()) {

            // fecth order 
            $row = $sql->row();
            // set default shipment rate and desicount persent fro  user 
            // get shipment rate from table data base
            $shipment_rate = $this->get_shiping_rate(number_format($row->Total_wiegth),$default_shipment_rate,$default_sescount);
            $shipment_rate_to = $this->get_shiping_rate(number_format($row->Total_wiegth + 1),$default_shipment_rate,$default_sescount);
            // get payment price sum((quanitty * price) + shipment_cost) dolar
            $total_payment = $this->convert_Currency($row->Payment_price, $dolar);
            // convert from dolar to rial
            // get count pefrum
            $perfum = $this->get_count_perfum($Temporary, $user_id, $order_id, 'perfum');

            // get perfum cost
            $perfum = $this->get_perfum(number_format($perfum));
            // convert from dolar to rial
            $perfum = $this->convert_Currency($perfum, $dolar);

            // get count battery
            $battery_ = $this->get_count_perfum($Temporary, $user_id, $order_id, 'battery');

            // get perfum battery
            $battery = $this->get_battery(number_format($battery_));
            // convert from dolar to rial
            $battery = $this->convert_Currency($battery, $dolar);
            // get  Commission by total order
            $Commission = $this->get_Commission($row->Total_order);
            // get total price Commission+battery+pefrum+payment price;
            $Totla = $Commission + $total_payment;

            return array(
                'Total_order' => $row->Total_order,
                'Total_quantity' => $row->Total_quantity,
                'Total_payment' => ceil($total_payment),
                'Total_perfum' => $perfum,
                'Total_battery' => $battery,
                'Total_weight' => number_format($row->Total_wiegth),
                'shipment_from' => $shipment_rate,
                'shipment_to' => $shipment_rate_to,
                'Commission' => $Commission,
                'Total' => ceil($Totla)
            );
        } else {
            return array(
                'Total_order' => 0,
                'Total_quantity' => 0,
                'Total_payment' => 0,
                'Total_perfum' => 0,
                'Total_battery' => 0,
                'Total_weight' => 0,
                'shipment_from' => 0,
                'shipment_to' => 0,
                'Commission' => 0,
                'Total' => 0);
        }
    }

    public function box_invoice($user_id, $order_id = '', $dolar = '', $default_shipment_rate = '', $default_sescount = '', $coupone_id = '', $coupone_discount = '') {
        $CI = & get_instance();

        // get informatio of items : count order sum weigth
        $CI->db->select('SUM(weight) AS Total_weight ,SUM(additional) AS Total_Additional ', false);
        $CI->db->where_in('id', $order_id);
        $CI->db->where('user_id', $user_id);
        $CI->db->group_by('user_id');
        $CI->db->from('items');
        $sql = $CI->db->get();
        if ($sql->num_rows()) {
            $row = $sql->row();

            // get shiping rate with default rate if found
            $shiping_rate = $this->get_shiping_rate($row->Total_weight, $default_shipment_rate, $default_sescount);

            // get battery i found
            $battery = $this->get_count_perfum_box($user_id, $order_id, 'battery');
            $battery = $this->get_battery($battery);
            $battery = $this->convert_Currency($battery, $dolar);
            // get perfum is found
            $perfum = $this->get_count_perfum_box($user_id, $order_id, 'perfum');
            $perfum = $this->get_perfum($perfum);
            $perfum = $this->convert_Currency($perfum, $dolar);
            // get additional ammount
            $additional = $row->Total_Additional;
            // total = weigth + perfum + battery +additional
            $total = $shiping_rate + $perfum + $battery + $additional;
            return array(
                'Total' => number_format($total),
                'Total_weight' => $row->Total_weight,
                'Total_after_coupone' => number_format(($total - $coupone_discount)),
                'Coupone_id' => $coupone_id,
                'Coupone_discount' => $coupone_discount,
                'Shiping_rate' => $shiping_rate,
                'Perfum' => $perfum,
                'Battery' => $battery,
                'Additional' => $additional,
                'Deafult_ship_rate' => $default_shipment_rate,
                'Deafult_discount' => $default_sescount
            );
        } else {
            return array(
                'Total' => '',
                'Total_after_coupone' => '',
                'Total' => '',
                'Coupone_id' => '',
                'Shiping_rate' => '',
                'Perfum' => '',
                'Battery' => '',
                'Additional' => '',
                'Deafult_ship_rate' => '',
                'Deafult_discount' => ''
            );
        }
    }

    /**
     * get ship ment rate
     * @param type $wiegth
     * @return int
     */
    public function get_count_perfum_box($user_id, $order_id, $table = 'perfum') {
        $CI = & get_instance();

        $perfum = array();
        $battery = array();
        // nkow if the item box or order
        foreach ($order_id as $value) {
            $sql = $CI->db->get_where('items', array('id' => $value, 'user_id' => $user_id));
            if ($sql->num_rows()) {


                $row = $sql->row();
                if ($row->type == 'item_paid') {

                    $perfum[] = $this->get_battery_perfum_box_bill($row->user_id, $row->id, 'item_paid', 'perfum');
                    $battery[] = $this->get_battery_perfum_box_bill($row->user_id, $row->id, 'item_paid', 'battery');
                } elseif ($row->type == 'item_box') {

                    $perfum[] = $this->get_battery_perfum_box_bill($row->user_id, $row->id, 'item_box', 'perfum');
                    $battery[] = $this->get_battery_perfum_box_bill($row->user_id, $row->id, 'item_box', 'battery');
                }
            }
        }

        if ($table == 'perfum') {
            return array_sum($perfum);
        } elseif ($table == 'battery') {
            return array_sum($battery);
        }
    }

    public function get_battery_perfum_box_bill($user_id, $item_id, $type = 'item_paid', $table = 'perfum') {
        $CI = & get_instance();
        // get by user id
        if (!empty($user_id)) {
            $CI->db->where('user_id', $user_id);
        }

        if (!empty($item_id) && $type == 'item_paid') {
            $CI->db->where('id', $item_id);
        } else {
            $CI->db->where('order_id', $item_id);
            $CI->db->group_by('order_id');
        }

        if ($table == 'perfum') {
            $CI->db->where('perfum', 'YES');
            $CI->db->select('SUM(`quantity`) AS Total_order', FALSE);
        } elseif ($table == 'battery') {
            $CI->db->where('battery', 'YES');
            $CI->db->select('COUNT(*) AS Total_order', FALSE);
        }


        if ($type == 'item_paid') {
            $CI->db->from('items');
        } else {
            $CI->db->from('order_box_items');
        }

        $sqls = $CI->db->get();
        if ($sqls->num_rows()) {

            $rows = $sqls->row();
            $total = $rows->Total_order;
            return $total;
        } else {
            return 0;
        }
    }

    public function get_count_perfum($Temporary, $user_id, $order_id, $table = 'perfum') {
        $CI = & get_instance();


        if ($Temporary == true) {
            $CI->db->where('temporary', 'YES');
        }
        // get by user id
        if (!empty($user_id)) {
            $CI->db->where('user_id', $user_id);
        }

        if (!empty($order_id) && count($order_id) <= 0) {
            $CI->db->where('order_id', $order_id);
        } else {
            $CI->db->where_in('order_id', $order_id);
            $CI->db->group_by('user_id');
        }

        if ($table == 'perfum') {
            $CI->db->where('perfum', 'YES');
            $CI->db->select('SUM(`quantity`) AS Total_order', FALSE);
        } elseif ($table == 'battery') {
            $CI->db->where('battery', 'YES');
            $CI->db->select('COUNT(*) AS Total_order', FALSE);
        }




        //$CI->db->group_by('user_id');

        $CI->db->from('items');

        $sqls = $CI->db->get();
        if ($sqls->num_rows()) {

            $rows = $sqls->row();
            $total = $rows->Total_order;
            return $total;
        } else {
            return 0;
        }
    }

    public function get_shiping_rate($wiegth, $default_shiping_rate = '', $default_sescount = '', $company = '') {
        $CI = & get_instance();
        // عملية الجبر
        $wiegth = ceil($wiegth);
        $result = 0;
        if ($wiegth > 0) {
            if (empty($default_shiping_rate)) {
                if (!empty($company)) {
                    $where['company_id'] = $company;
                }
                $where['lbs'] = $wiegth;
                $sql = $CI->db->get_where('shipment_rate', $where);
                // get total cost
                if ($sql->num_rows()) {
                    $row = $sql->row();
                    $result = $row->total;

                    // if wigth > 300    
                } elseif ($wiegth > 300) {
                    $one_lbs=$this->get_lbs_max_300(300, $company);
                    $result = ceil($wiegth*$one_lbs);
                }
            } else {
                $result = $wiegth * $default_shiping_rate;
            }

            if (!empty($default_sescount)) {
                $persent = $result * ($default_sescount / 100);
                $result = $result - $persent;
            }
            return $result;
        } else {
            return 0;
        }
    }

    function get_lbs_max_300($max_wiegth = 300, $company) {
        $CI = & get_instance();
        $where['lbs'] = $max_wiegth;
        if (!empty($company)) {
            $where['company_id'] = $company;
        }
        $sql = $CI->db->get_where('shipment_rate', $where);
        $row=$sql->row();
        return $row->total/$max_wiegth;
    }

    /**
     * get commention
     * 
     * @param type $total
     * @return int
     */
    public function get_Commission($total) {
        if ($total >= 1 && $total <= 5) {
            return 50;
        } elseif ($total > 5) {
            return 50 + (($total - 5) * 10);
        } else {
            return 0;
        }
    }

    /**
     * get perfun cost
     * @param type $pices
     * @return int
     */
    public function get_perfum($pices) {

        if ($pices <= 0) {
            return 0;
        } else {
            return 15 + (($pices - 1) * 5);
        }
    }

    /**
     * 
     * @param type $pices
     * @return type
     */
    public function get_battery($pices) {
        if ($pices >= 1) {
            return 10;
        } else {
            return 0;
        }
    }

    /**
     * 
     * @param type $money
     * @return type
     */
    public function convert_Currency($money, $default = '') {
        if (empty($default)) {
            return $money * get_option('dolar');
        } else {
            return $money * $default;
        }
    }

    /**
     *  Display url to pay the bill or display button to view bill if you paid
     * ==============================
     * @param type $order_id        
     * @param type $user_id         
     * @param type $statues         
     * @return string               
     * ==============================
     *                  array ['display'] 1:to display paid bill or 2: to display view bill & [id]  
     *                  return bill id if found
     */
    public function display_inovices_button($order_id, $user_id, $statues = '') {
        $CI = & get_instance();
        $result = array();
        // valid if invoice is found 
        // if true return 2 and invoice id
        $sql = $CI->db->get_where('order_invoices', array('order_id' => $order_id, 'user_id' => $user_id));
        if ($sql->num_rows()) {
            $row = $sql->row();
            // if paid display view invoices 
            if ($row->paid == 'YES') {

                $result['display'] = 2;
                $result['id'] = $row->id;
            } else {
                // else dispaly add invoice   
                $result['display'] = 1;
                $result['id'] = $row->id;
            }
        } else {

            // if not found dont replay any thing

            $result['display'] = 0;
            $result['id'] = '';
        }
        return $result;
    }

    /**
     * 
     * @param type $order_id
     * @param type $user_id
     * @param type $statues
     * @param type $corn // if run courn job to add invoices automatic set value true
     * @param type $not_statues
     * @return boolean
     */
    public function create_order_invoices($order_id, $user_id, $statues, $corn = false, $not_statues = array(12, 13, 14)) {
        $CI = & get_instance();
        if ($corn == false) {
            // if found invoice return false
            $sql = $CI->db->get_where('order_invoices', array('order_id' => $order_id, 'user_id' => $user_id));

            if ($sql->num_rows()) {
                return false;
            } else {
                //else add invoice to this user and order by must get cahe 
                // get where item statues is Rejected or void or Join
                if (count($not_statues) > 0) {
                    $CI->db->where_not_in('statue_id', $not_statues);
                }

                $CI->db->having('SUM(statue_id) = COUNT(statue_id)*' . $statues);
                $sql = $CI->db->get_where('items', array('order_id' => $order_id, 'user_id' => $user_id, 'temporary' => 'NO', 'type' => 'item_paid'));

                if ($sql->num_rows()) {

                    // get cashe of invoices
                    $bill = $this->payment_invoice($user_id, false, $order_id);
                    $cashe = $bill['Total'];
                    //carete bill
                    $insert = array(
                        'order_id' => $order_id,
                        'user_id' => $user_id,
                        'bill_cahe' => $cashe,
                        'dolar' => get_option('dolar'),
                        'create_date' => date('Y-m-d H:i:s')
                    );
                    $CI->db->insert('order_invoices', $insert);
                    $id = $CI->db->insert_id();
                    $create_history = $this->create_history(array('user_id' => $user_id, 'invoice_id' => $id, 'operation' => 'create', 'create_date' => date('Y-m-d H:i:s')));
                    return true;
                } else {

                    return false;
                }
            }
        }
    }

    public function create_history($data = array()) {
        $CI = & get_instance();
        if (is_array($data['invoice_id'])) {
            foreach ($data['invoice_id'] as $value) {
                $data['invoice_id'] = $value;
                $CI->db->insert('invoices_histroy', $data);
            }
        } else {
            $CI->db->insert('invoices_histroy', $data);
        }
    }

    /**
     * 
     * @param type $item_id
     * @param type $user_id
     * @param type $bill_cahe
     * @param type $dolar
     * @return type
     */
    public function create_box_invoices($item_id = array(), $user_id, $bill_cahe, $dolar = '') {


        // insert bill in table order_invoices set user_id , bill_cahe,create_date,dolar,type=box
        if (empty($dolar)) {
            $dolar = get_option('dolar');
        }
        $CI = & get_instance();
        // get default discount_persent shipming rate
        $user_date = get_userdata_with_id($user_id, 'discount_persent,shipment_rate');

        $CI->db->insert('order_invoices', array('user_id' => $user_id, 'bill_cahe' => $bill_cahe, 'type' => 'box', 'dolar' => $dolar, 'create_date' => date('Y-m-d H:i:s'), 'shipment_rate' => $user_date['shipment_rate'], 'discount_persent' => $user_date['discount_persent']));
        $id = $CI->db->insert_id();
        // insert item under box in table invoice_box_items invoice_id item id
        foreach ($item_id as $value) {
            $CI->db->insert('invoice_box_items', array('invoice_id' => $id, 'item_id' => $value));
        }
        // insert hestory of bill
        $CI->db->insert('invoices_histroy', array('invoice_id' => $id, 'operation' => 'create', 'create_date' => date('Y-m-d H:i:s'), 'user_id' => $CI->admin_id));
        // update item id to new statues 26 بانتظار سداد فاتورة شحن
        $CI->db->where_in('id', $item_id);
        $CI->db->update('items', array('statue_id' => 26));
        return $id;
    }

}

?>
